package cn.com.sinux.spring.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class JsonUtils {

    public static boolean isJsonString(String value) {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine se = sem.getEngineByName("js");
        try {
            se.eval(value);
            return true;
        } catch (ScriptException e) {
            return false;
        }
    }

    public static String toString(Object obj) {
        if (obj == null) {
            return StringUtils.EMPTY;
        }
        try {
            return toString(null, obj);
        } catch (IOException io) {

        }
        return StringUtils.EMPTY;
    }

    public static String toString(String rootName, Object obj) throws IOException {
        Object _obj = obj;
        if (StringUtils.isNotBlank(rootName)) {
            _obj = Collections.singletonMap(rootName, obj);
        }
        return JSONObject.toJSONString(_obj);
    }

    /**
     * json字符串转化成一个对象
     *
     * @param cls
     * @param json
     * @param <T>
     * @return
     */
    public static <T> T stringToObject(Class<T> cls, String json) {
        return JSONObject.parseObject(json, cls);
    }

    public static <T> List<T> StringToArray(Class<T> cls, String json) {
        return JSON.parseArray(json, cls);
    }

    public static void main(String[] args) {

    }


    /**
     * 对象转化成Json字符串
     *
     * @param o java对象
     * @return 空串或者json字符串
     */
    public static String objectToJsonString(Object o) {
        String answer = "";
        if (o == null) {
            return answer;    //null
        }
        return toString(o);
    }


}
